import React, { useState } from "react";
import "./index.less";
// 封装input输入框事件
const useInput = (value, location, type) => {
  const [inputValue, setInputValue] = useState(value || 0);


  // 修改input值
  const changeValue = (e) => {
    const {value} = e.target;
    if(!value) return;
    setInputValue(value);
  };

  // 离开概率输入框事件
  const onBlur = (updateGridProbValue) => {
    updateGridProbValue(inputValue, location, type);
  };

  // 输入框回车事件
  const onKeyUp = (e, updateGridValue) => {
    if (e.keyCode === 13) onBlur(updateGridValue);
  };
  return [
    inputValue,
    changeValue,
    onBlur,
    onKeyUp,
  ];
};
/**
 * 封装展示框，可双击变成input输入框
 * @param {name} 展示框名字
 * @param {value} 值
 * @param {location} 展示框所在位置
 * @param {referType} 展示框的关系类型
 * @param {updateGridValue} context的更新数据方法
 * @param {inputType} 默认值:text，输入框的默认类型
 * @returns
 */
export default function DoubleInput({
  name,
  value,
  location,
  referType,
  updateGridValue,
  inputType = "text",
}) {
  const [
    inputValue,
    changeValue,
    onBlur,
    onKeyUp,
  ] = useInput(value, location, referType);
  /* 双击修改，并展现input框 */
  return (
    <p className="grid-show-box">
      <span className="grid-name">{name}:</span>
      <input
          className="grid-input"
          type={inputType}
          value={inputValue}
          onChange={changeValue}
          onBlur={() => onBlur(updateGridValue)}
          onKeyUp={(e) => onKeyUp(e, updateGridValue)}
        />
    </p>
  );
}
